package com.haiheng.library_base.utils

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2022/7/14 0014
 * @Version: 1.0
 */
class KeyboardUtils {
    companion object{
        fun showKeyboard(view: View) {
            val imm = view.context
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (imm != null) {
                view.requestFocus()
                imm.showSoftInput(view, 0)
            }
        }

        fun hideKeyboard(view: View) {
            val imm = view.context
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm?.hideSoftInputFromWindow(view.windowToken, 0)
        }

        fun toggleSoftInput(view: View) {
            val imm = view.context
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm?.toggleSoftInput(0, 0)
        }

        /**
         * Hide the soft input.
         *
         * @param activity The activity.
         */
        fun hideSoftInput(activity: Activity) {
            var view = activity.currentFocus
            if (view == null) {
                val decorView = activity.window.decorView
                val focusView = decorView.findViewWithTag<View>("keyboardTagView")
                if (focusView == null) {
                    view = EditText(activity)
                    view.setTag("keyboardTagView")
                    (decorView as ViewGroup).addView(view, 1, 1)
                } else {
                    view = focusView
                }
                view.requestFocus()
            }
            hideSoftInput(view)
        }

        /**
         * Hide the soft input.
         *
         * @param view The view.
         */
        fun hideSoftInput(view: View) {
            val imm =
                ApplicationUtils.application.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    ?: return
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

}